const cache = require('../../utils/cache.js')

async function invokeDefers() {
    let defers = this.options.defers
    if (defers) {
        defers.forEach(defer => {
            defer(this)
        })
        defers.length = 0
    }
}

async function onPageOpen() {
    invokeDefers.call(this)
}

async function onOpen() {
    let client = cache.connections.get(this.options.host)
    let shell = await client.connection.shell()
    if (shell) {
        shell.on('data', data => {
            this.onFn('onOutput', data.toString())
        })
        cache.shell = shell
        invokeDefers.call(this)
    }
}

async function onExec(data) {
    cache.shell.write(data)
}

async function onCommand(data, helps, isCommand = true) {
    if (isCommand) {
        cache.shell.write(data)
    }
    this.onFn('onHelp', {
        template: data,
        helps: helps || []
    })
}

async function onError(error) {
    throw new Error(error.message || '打开终端失败, 未知异常')
}

async function onClosed() {
    cache.shell.close()
}

async function onSaveCommand(data) {
    console.log(data)
}

module.exports = {
    onPageOpen,
    onOpen,
    onExec,
    onError,
    onClosed,
    onSaveCommand,
    onCommand
}
